<!--
 * @Author: zhangyun
 * @Date: 2021-04-25 09:14:56
 * @LastEditors: zhangyun
 * @LastEditTime: 2021-04-28 10:43:03
 * @Desc: 
-->
<template>
  <header class="flex justify-end">
    <button
      class="iconfont icon-fenxiang text-white bg-blue-600 focus:outline-none px-4 py-1 rounded mb-3 active:bg-blue-200"
      @click="pushArticle"
    >
      发布
    </button>
  </header>
  <div class="h-64 w-full bg-gray-100 text-center" @click="handleFile">
    <input
      class="hidden"
      type="file"
      @change="changeUpdateImg"
      ref="fileNode"
      id="profile_pic"
      accept=".jpg, .jpeg, .png"
      multiple
    />
    <i class="inline-block iconfont icon-tupian text-4xl text-gray-400 mt-20 cursor-pointer"></i>
  </div>
  <div class="h-16 w-full">
    <input
      class="h-full w-full p-2 text-3xl font-black focus:outline-none"
      type="text"
      v-model="articleForm.title"
      placeholder="请输入标题（最多100字）"
    />
  </div>
  <div id="editor" ref="root"></div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, reactive, getCurrentInstance } from 'vue'
import E from 'wangeditor'
import * as _ from 'lodash'
import { resetForm } from '@utils/index.ts'

interface article {
  img?: string
  title: string
  detail: string
}

export default defineComponent({
  name: 'WriteArticle',
  setup() {
    const root = ref(null)
    const articleForm = reactive<article>({
      img: '',
      title: '',
      detail: '',
    })
    let Editor: any
    const { ctx } = getCurrentInstance() as any
    onMounted(() => {
      // DOM元素将在初始渲染后分配给ref
      Editor = new E(root.value)
      Editor.config.height = 500
      Editor.create()
      Editor.config.onchange = (html: any): void => {
        articleForm.detail = html
      }
    })
    function changeUpdateImg(e: any) {
      const file = e.target.files[0]
      if (file.size > 1024 * 1024 * 3) {
        fileNode.value.placeholder = '文件大小不能超过3M!'
        articleForm.img = ''
        return false
      }
      articleForm.img = file
    }
    const fileNode = ref()
    function handleFile() {
      fileNode.value.click()
    }
    // 提交
    async function pushArticle() {
      const userInfoStr = localStorage.getItem('user_info') || ''
      const userInfo = JSON.parse(userInfoStr)
      if (_.isEmpty(userInfo.user)) {
        alert('请登陆')
        return
      }
      const res = await ctx.$http.post('/api/article', {
        img: '',
        title: articleForm.title,
        detail: articleForm.detail,
        time: new Date().getTime(),
        creator: userInfo.user,
      })
      alert(res.message)
      resetForm(articleForm)
      Editor.txt.clear()
    }
    return { root, changeUpdateImg, articleForm, handleFile, fileNode, pushArticle }
  },
})
</script>

<style></style>
